<?
/**
 * VoiceOne Settings/Groups/edit
 *
 * Frontend to provide access to the groups system in voiceone.
 * @package voiceone
 * @subpackage  settings_groups
 */
 
  include ("../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage,$relBasePath;    
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  sajax_init();
  
  //================ XAJAX ================
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $group=$formData["group"];
    $id=$group["id"];
    $name=$group["name"];
    $type=$group["type"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all groups
    $groupsArr=$asterisk->getGroup(0,0);;
    if(is_array($groupsArr)){
      foreach($groupsArr as $g) {
        if($id!=$g["id"]) $gNameArr[]=$g["name"];
      }
    }
    // Check Name ((not null)&&(unique))
    $nameErr=false;
    if($name=="") { 
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr_".$type,"innerHTML",$imgErr);
      $nameErr=true;  
    }else if((is_array($gNameArr))&&(in_array($name,$gNameArr))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr_".$type,"innerHTML",$imgErr);
      $nameErr=true;
    }
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML",""); 
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();

  //=================== POST ====================
  if (count($_POST)>0) {
    $data=$_POST["group"];
    $entry=Array(
            "id" =>   $data["id"],
            "type" => $data["type"],
            "name" => $data["name"]
        );
    if (is_array($_POST["entity"]))
    foreach($_POST["entity"] as $e) $entry["entity"][]=$e;
    $ret=$asterisk->putGroup($entry);
    if ($ret>0) {
      if($data["id"]!="") $alert="<div class=\"AlertGood\">".T_("The group has been modified")."</div>";
      else $alert="<div class=\"AlertGood\">".T_("The group has been created")."</div>";
      $_GET["id"]=$ret;
    } else {
      if($data["id"]!="") $alert="<div class=\"AlertBad\">".T_("The group hasn't been modified")."</div>";
      else $alert="<div class=\"AlertBad\">".T_("The group hasn't been created")."</div>";
    }
    goToMainPage($alert);
  }
  
  //================ PAGE LOGIC ================
  $imgClient="<img src=\"$relBasePath/public/img/icon_group.gif\" alt=\"group of exten\" />";
  $imgDep="<img src=\"$relBasePath/public/img/icon_offices.gif\" alt=\"department\" />";
  $imgRes="<img src=\"$relBasePath/public/img/icon_resurces.gif\" alt=\"resource\" />";
  $imgNum_group="<img src=\"$relBasePath/public/img/icon_numbers.gif\" alt=\"phone number\" />";
  $imgNum="<img src=\"$relBasePath/public/img/icon_number.gif\" alt=\"phone number\" />";
  $imgAppl_group="<img src=\"$relBasePath/public/img/icon_appls.gif\" alt=\"application\" />";
  $imgAppl="<img src=\"$relBasePath/public/img/icon_appl.gif\" alt=\"application\" />";
  //retrieve the group informations
  if ($_GET["id"]!="") {
    $grp=$asterisk->getGroup($_GET["id"],0);
    $grptype=$grp[0]["type"];
    $grpname=$grp[0]["name"];
    $grpentity=$grp[0]["entity"];
    $grpright=$grp[0]["right"];
    $title=sprintf(T_("Modify group: %1\$s"),$grpname );
  } else {
    $title=T_("New group");
    $grptype=GROUP_OF_EXTENSION; //set the default group type
  }
  //retrieve the extension informations
  $ret=$asterisk->getClient(0,0);
  if ($err=$asterisk->getError()) die("Error: $err");
  $count=0;
  if (is_array($ret))
  foreach($ret as $v) {
    $id=$v["id"];
    $callerid=$v["name"]." ".$v["surname"]." &lt;".$v["extension"]."&gt;";
    $technology=$v["technology"];
    $prot=getIcon($technology);
    if (@in_array($id, $grpentity)) $chk="checked='checked'"; else $chk=""; 
    $html_client.="<td> <input type=\"checkbox\" name=\"entity[]\" value=\"$id\" $chk/> $prot $callerid </td>\n";
    if ((++$count)%2==0) $html_client.="</tr><tr>\n";
  }
  //retrieve the department informations
  $ret=$asterisk->getOffice(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  $count=0;
  if (is_array($ret))
  foreach($ret as $v) {
    $id=$v["id"];
    $name=$v["name"];
    $prot=getIcon(IAX2);
    if (@in_array($id, $grpentity)) $chk="checked='checked'"; else $chk=""; 
    $html_dep.="<td> <input type=\"checkbox\" name=\"entity[]\" value=\"$id\" $chk/> $prot $name</td>\n";
    if ((++$count)%2==0) $html_dep.="</tr><tr>\n";
  }
  //retrieve the provider informations
  $ret=$asterisk->getProviderAccount(0,0);
  if ($err=$asterisk->getError()) die("Error: $err");
  $count=0;
  if (is_array($ret))
  foreach($ret as $v) {
    $id=$v["id"];
    $name=$v["name"];
    $prov=$asterisk->getProvider($v["provider"]);
    $technology=$prov[0]["technology"];
    $pname=$prov[0]["name"];
    $prot=getIcon($technology);
    if (@in_array($id, $grpentity)) $chk="checked='checked'"; else $chk=""; 
    $html_res.="<td> <input type=\"checkbox\" name=\"entity[]\" value=\"$id\" $chk/> $prot ($pname)&nbsp;$name </td>\n";
    if ((++$count)%2==0) $html_res.="</tr><tr>\n";
  }
  //retrieve the phone number informations
  $ret=$asterisk->getPhoneNumber(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  $count=0;
  if (is_array($ret))
  foreach($ret as $v) {
    $id=$v["id"];
    $name=$v["name"];
    if (@in_array($id, $grpentity)) $chk="checked='checked'"; else $chk=""; 
    $html_num.="<td> <input type=\"checkbox\" name=\"entity[]\" value=\"$id\" $chk/> $imgNum $name </td>\n";
    if ((++$count)%2==0) $html_num.="</tr><tr>\n";
  }
  //retrieve the phone number informations
  $ret=$asterisk->getApplication(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  $count=0;
  if (is_array($ret))
  foreach($ret as $v) {
    $id=$v["id"];
    $name=$v["name"];
    $label=$v["label"];
    if (@in_array($id, $grpentity)) $chk="checked='checked'"; else $chk=""; 
    $html_appl.="<td> <input type=\"checkbox\" name=\"entity[]\" value=\"$id\" $chk/> $imgAppl $label </td>\n";
    if ((++$count)%2==0) $html_appl.="</tr><tr>\n";
  }
  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../admin/lib/xajax/"); 
  ?>
  <div class="SectionHeader">
  <?=$alert?>
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin" ><?=T_("Return without save")?></a> 
    </h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?><? if ($_GET["id"]!="") echo "?id=".$_GET["id"]; ?>" method="post">
    	<h2><?=T_("Group type")?></h2>
      <p class="blockintro"><?=T_("It is mandatory to specify the group type before proceeding")?></p>
      <table>
        <tr>
          <td width="20%">
            <div id="client_container" class="block button <?if ($grptype==GROUP_OF_EXTENSION) echo 'blockover';?>" onmouseover="groupSwitch('client')" onmouseout="groupRestore()" onclick="groupCheck('client')">
              <input type="radio" name="type" value="<?=GROUP_OF_EXTENSION?>" id="client" <?if ($grptype==GROUP_OF_EXTENSION) echo "checked='checked'";?>/> 
              <label for="type"><?=$imgClient?> <?=T_("Extensions")?></label>
            </div>
          </td>
          <td width="20%">
            <div id="dep_container" class="block button <?if ($grptype==GROUP_OF_OFFICE) echo 'blockover';?>" onmouseover="groupSwitch('dep')" onmouseout="groupRestore()" onclick="groupCheck('dep')">
              <input type="radio" id="dep" name="type" value="<?=GROUP_OF_OFFICE?>" <?if ($grptype==GROUP_OF_OFFICE) echo "checked='checked'";?>/> 
              <label for="type"><?=$imgDep?> <?=T_("Office")?></label>
            </div>
          </td>
          <td width="20%">
            <div id="res_container" class="block button <?if ($grptype==GROUP_OF_RESOURCE) echo 'blockover';?>" onmouseover="groupSwitch('res')" onmouseout="groupRestore()" onclick="groupCheck('res')">
              <input type="radio" id="res" name="type" value="<?=GROUP_OF_RESOURCE?>" <?if ($grptype==GROUP_OF_RESOURCE) echo "checked='checked'";?>/> 
              <label for="type"><?=$imgRes?> <?=T_("Provider")?></label>
            </div>
          </td>
          <td width="20%">
            <div id="num_container" class="block button <?if ($grptype==GROUP_OF_PHONENUMBER) echo 'blockover';?>" onmouseover="groupSwitch('num')" onmouseout="groupRestore()" onclick="groupCheck('num')">
              <input type="radio" id="num" name="type" value="<?=GROUP_OF_PHONENUMBER?>" <?if ($grptype==GROUP_OF_PHONENUMBER) echo "checked='checked'";?>/> 
              <label for="type"><?=$imgNum_group?> <?=T_("Number")?></label>
            </div>
          </td>
          <td width="20%">
            <div id="appl_container" class="block button <?if ($grptype==GROUP_OF_APPLICATION) echo 'blockover';?>" onmouseover="groupSwitch('appl')" onmouseout="groupRestore()" onclick="groupCheck('appl')">
              <input type="radio" id="appl" name="type" value="<?=GROUP_OF_APPLICATION?>" <?if ($grptype==GROUP_OF_APPLICATION) echo "checked='checked'";?>/> 
              <label for="type"><?=$imgAppl_group?> <?=T_("Application")?></label>
            </div>
          </td>
        </tr>
      </table>
      
      <div id="client_form" style="display: <?if ($grptype==GROUP_OF_EXTENSION) echo 'block'; else echo 'none';?>" >
        <h2><?=T_("Extensions group")?></h2>
        <p class="blockintro"><?=T_("Choose the extensions that belongs to this group")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="group[name]"><?=T_("Name")?>:</label></dt>
            <dd>
              <input type="text" size="25" maxlength="30" id="group[name]" name="group[name]" value="<?=$grpname?>" />
              <span id="nameErr_<?=GROUP_OF_EXTENSION?>"></span> <span class="help"><?=T_("I.e. Helpdesk, Administration, etc...")?></span>
            </dd>
          </dl>
          <p class="blockintro"><?=T_("To choose the extensions, click on the desired checkbox")?></p>
          <table class="todolist" >
            <tr><?=$html_client?></tr>
          </table>
          <input type="hidden" name="group[type]" value="<?=GROUP_OF_EXTENSION?>" />
        </div>
      </div>      

      <div id="dep_form" style="display: <?if ($grptype==GROUP_OF_OFFICE) echo 'block'; else echo 'none';?>" >
        <h2><?=T_("Office group")?></h2>
        <p class="blockintro"><?=T_("Choose the offices that belongs to this group")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="group[name]"><?=T_("Name")?>:</label></dt>
            <dd>
              <input type="text" size="25" maxlength="30" id="group[name]" name="group[name]" value="<?=$grpname?>" />
              <span id="nameErr_<?=GROUP_OF_OFFICE?>"></span> <span class="help"><?=T_("I.e. Asia, Europe, National, etc...")?></span>
            </dd>
          </dl>
          <p class="blockintro"><?=T_("To choose the offices, click on the desired checkbox")?></p>
          <table class="todolist" >
            <tr><?=$html_dep?></tr>
          </table>
          <input type="hidden" name="group[type]" value="<?=GROUP_OF_OFFICE?>" />
        </div>
      </div>      

      <div id="res_form"  style="display: <?if ($grptype==GROUP_OF_RESOURCE) echo 'block'; else echo 'none';?>" >
        <h2><?=T_("Provider group")?></h2>
        <p class="blockintro"><?=T_("Choose the providers that belongs to this group")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="group[name]"><?=T_("Name")?>:</label></dt>
            <dd>
              <input type="text" size="25" maxlength="30" id="group[name]" name="group[name]" value="<?=$grpname?>" />
              <span id="nameErr_<?=GROUP_OF_RESOURCE?>"></span> <span class="help"><?=T_("I.e. Free, Payment, etc...")?></span>
            </dd>
          </dl>
          <p class="blockintro"><?=T_("To choose the providers, click on the desired checkbox")?></p>
          <table class="todolist" >
            <tr><?=$html_res?></tr>
          </table>
          <input type="hidden" name="group[type]" value="<?=GROUP_OF_RESOURCE?>" />
        </div>
      </div>      
      
      <div id="num_form"  style="display: <?if ($grptype==GROUP_OF_PHONENUMBER) echo 'block'; else echo 'none';?>" >
        <h2><?=T_("Phone number group")?></h2>
        <p class="blockintro"><?=T_("Choose the phone numbers that belongs to this group")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="group[name]"><?=T_("Name")?>:</label></dt>
            <dd>
              <input type="text" size="25" maxlength="30" id="group[name]" name="group[name]" value="<?=$grpname?>" />
              <span id="nameErr_<?=GROUP_OF_PHONENUMBER?>"></span> <span class="help"><?=T_("I.e. Toll-free, international, etc...")?></span>
            </dd>
          </dl>
          <p class="blockintro"><?=T_("To choose the phone numbers, click on the desired checkbox")?></p>
          <table class="todolist" >
            <tr><?=$html_num?></tr>
          </table>
          <input type="hidden" name="group[type]" value="<?=GROUP_OF_PHONENUMBER?>" />
        </div>
      </div>   
      
      <div id="appl_form"  style="display: <?if ($grptype==GROUP_OF_APPLICATION) echo 'block'; else echo 'none';?>" >
        <h2><?=T_("Application groups")?></h2>
        <p class="blockintro"><?=T_("Choose the applications that belongs to this group")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="group[name]"><?=T_("Name")?>:</label></dt>
            <dd>
              <input type="text" size="25" maxlength="30" id="group[name]" name="group[name]" value="<?=$grpname?>" />
              <span id="nameErr_<?=GROUP_OF_APPLICATION?>"></span> <span class="help"><?=T_("I.e. Commercial, Internal, etc...")?></span>
            </dd>
          </dl>
          <p class="blockintro"><?=T_("To choose the applications, click on the desired checkbox")?></p>
          <table class="todolist" >
            <tr><?=$html_appl?></tr>
          </table>
          <input type="hidden" name="group[type]" value="<?=GROUP_OF_APPLICATION?>" />
        </div>
      </div>   
      
      <div class="action">
        <? if ($_GET["id"]!="") {?><input type="hidden" name="group[id]" value="<?=$_GET["id"]?>" /><?}?>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
      <!--
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" />
      -->
      </div>
    </form>
  </div>  
  <script>
        window.onload=function() {
          switchEnable(document.getElementById('client_form'), true, 1);
          switchEnable(document.getElementById('dep_form'), true, 1);
          switchEnable(document.getElementById('res_form'), true, 1);
          switchEnable(document.getElementById('num_form'), true, 1);
          switchEnable(document.getElementById('appl_form'), true, 1);
          <?
            if ($grptype==GROUP_OF_EXTENSION) $txt="client";
            else if ($grptype==GROUP_OF_OFFICE) $txt="dep";
            else if ($grptype==GROUP_OF_RESOURCE) $txt="res";
            else if ($grptype==GROUP_OF_PHONENUMBER) $txt="num";
            else if ($grptype==GROUP_OF_APPLICATION) $txt="appl";
            if ($txt!="") echo "switchEnable(document.getElementById('".$txt."_form'), false, 1);\n";
          ?>
        }
  </script>
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
        <div class="Sidebar">
          <h1><?=T_("Informations")?></h1>
          <?=T_("To be done...")?>
        </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();

  $smarty->assign("section", "groups");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

